package com.txby.platformApi.component.web;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.gexin.fastjson.JSON;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ArithSolve;
import com.jck.tools.ChkUtil;
import com.jck.tools.Times;
import com.txby.platformApi.component.service.SickBPdataRelationService;
import com.txby.platformCore.component.service.CommonController;
import com.txby.platformCore.component.util.ObjectRequireFieldVerifyUtil;
import com.txby.platformCore.data.CommonApiModelMapExt;
import com.txby.platformCore.entity.SickBPdata;
import com.txby.platformCore.entity.SickDetailInfo;

import edu.emory.mathcs.backport.java.util.Arrays;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 患者血压数据
* @author 作者 jacking
* @date  
 */
@SuppressWarnings("all")
@RestController
@Api(value="api信息",description="api信息-说明")
public class SickBPdataController extends CommonController{
	private static Logger log = Logger.getLogger(SickBPdataController.class);
	@Resource
	private SickBPdataRelationService srs;

	@ApiOperation(value = "app测量血压扫码绑定患者", notes = "app测量血压扫码绑定患者")
	@PostMapping("/scanBPcode/{type}/{token}")
//	@GlobalLogAnnotation(logType=2,discription="护士站提醒消息")
	public Map scanBPcode(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam  String deviceSN,@RequestParam  String qrUrl) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			SickDetailInfo sbi =this.getSickDetailInfo(deviceSN);
			if(ChkUtil.isEmpty(sbi)){
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "此设备患者不存在");
				return mm;
			}
			return srs.getDeviceInfo(sbi.getId_(),deviceSN, qrUrl);
		
		}catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "请求血压设备绑定成功");
			 
		    return mm;	
		}
		
	}
	
	@PostMapping("/kang/bloodpressure")
	public Map bloodpressure(SickBPdata sbp,HttpServletRequest request) {
		Map data=new HashMap();
		List<String> excludeField=Arrays.asList(new String []{"checkTime","sickId","deviceSN","remarks","bpunique","bpkey"});
		Map callBack=ObjectRequireFieldVerifyUtil.isAllFieldRequiredOfNull(sbp, excludeField);
		boolean flag=(boolean) callBack.get("flag");
		String fields=(String) callBack.get("fields");
		if(flag){
			 data.put("code", 0);
			 data.put("status", "参数必填不正确");
			 data.put("msg", "参数必填不正确,"+fields+"");
			 
			 return  data;
			
		}
		
		sbp.setCreater("kangkang");
		sbp.setUpdater("kangkang");
		sbp.setBpunique(sbp.getUnique());
		sbp.setUnique(null);
		sbp.setBpkey(sbp.getKey());
		sbp.setKey(null);
		sbp.setCheckTime(Times.getStringToDate(sbp.getTime(), new SimpleDateFormat("yyyyMMddHHmmss")));
		sbp.setRemarks("kangkang数据推送保存");
		System.out.println(JSON.toJSON(sbp));
		try {
			 data.put("code", 0);
			 data.put("status", "接收失败");
			 data.put("msg", "接收失败");
			/* data
			code: (number,required) - 响应码,1成功,2拒收(不重发),其他失败(会重新发送)
			status: (string,optional) - 状态:success为成功,其他为失败
			msg: (string,optional) - 个性化响应消息
			data: (string,optional) - 其他需要返回的数据,JSON对象*/
			 return srs.saveBloodpressure(sbp);
		}catch (Exception e) {
			e.printStackTrace();
			return data;	
		}
		
	}
	@GetMapping("/getSickBPdata/{type}/{token}")
	public Map getSickBPdata(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam  String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		 
		try {
			if (!isTokenValid) {
				return mm;
			}
			SickDetailInfo sbi =this.getSickDetailInfo(deviceSN);
			if(ChkUtil.isEmpty(sbi)){
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "此设备患者不存在");
				return mm;
			}
			 
			String sql="select systolicpressure,diastolicpressure,pulse,checkTime,level from "+this.mBaseDao.tableName(SickBPdata.class)+" where sickId="+sbi.getId_()+" order by updateTime desc ";
			PageList<Map> pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, null, null);
			
			if(pl.getResultList().size()>0){
				for(Map s:pl.getResultList()){
//					  血压等级,0:低,1:正常,2:正常高值,3:轻度,4:中度,5:高度
					String levelName="";
					Integer level=new Integer(s.get("level").toString());
					if(level>1){
						levelName="偏高";
					}else if(level==0){
						
						levelName="偏低";
					}else{
						levelName="正常";
					}
					s.put("levelName", levelName);
					
					
				}
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data",pl.getResultList());
			}else{
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "无数据");
			}
			return mm;
		
		}catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统开小差，稍后重试");
			 
		    return mm;	
		}
		
	}
	/**
	 * 血压报表数据
	 * 
	 * reportType 报表类型  0 ：日（当日数据），1周（近周天数据），2：月（近1个月天数据），3：年（近年月数据）
	* @Title: getSickBPdataBy 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param type
	* @param @param token
	* @param @param deviceSN
	* @param @param reportType
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	@GetMapping("/getSickBPdataByReport/{type}/{token}")
	public Map getSickBPdataByReport(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam  String deviceSN,@RequestParam Integer reportType) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		
		try {
			if (!isTokenValid) {
				return mm;
			}
			SickDetailInfo sbi =this.getSickDetailInfo(deviceSN);
			if(ChkUtil.isEmpty(sbi)){
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "此设备患者不存在");
				return mm;
			}
			
			String dateType=" %H ";
			String gropType=" 0 day ";
			String curdate=" curdate()+1 ";
			if(reportType==0){
				gropType=" 0 day ";
				dateType=" %H ";
				curdate=" curdate() ";
			} else if(reportType==1){
				gropType=" 1 week ";
				dateType="  %Y-%m-%d  ";
			}else if(reportType==2){
				gropType=" 1 month ";
				dateType="  %Y-%m-%d  ";
			}else if(reportType==3){
				gropType=" 1 year ";
				dateType="  %Y-%m  ";
			}
			 
			String  sickWhere="";
			if(sbi!=null){
				
				sickWhere=" and t.sickId="+sbi.getId_()+"  ";
			}
			
			
			String sql="select systolicpressure,diastolicpressure,pulse,checkTime,level from "+this.mBaseDao.tableName(SickBPdata.class)+" where sickId="+sbi.getId_()+" order by updateTime desc ";
			sql="SELECT bp.*,t.cyear from t_txby_sickBPdata bp ,(SELECT  t.cyear from (SELECT  t.*, DATE_FORMAT(t.checkTime,'%Y-%m') cyear FROM  t_txby_sickBPdata t  WHERE   t.checkTime >=(select date_sub(curdate(),interval 12 month))+' 00:00:00' and  t.checkTime <=(select date_sub(curdate(),interval 0 month))+' 23:59:59'   ) t GROUP BY  t.cyear) t WHERE t.cyear=DATE_FORMAT(bp.checkTime,'%Y-%m') ";
			
			sql="SELECT t.category,sum(t.systolicpressure) totalSystolicpressure,sum(t.diastolicpressure) totalDiastolicpressure,count(t.id_) count,sum(t.systolicpressure) /count(t.id_) averageSystolicpressure,sum(t.diastolicpressure)/count(t.id_)  averageDiastolicpressure FROM ( SELECT t.*, DATE_FORMAT(t.checkTime, '"+dateType+"') category 	FROM 	t_txby_sickBPdata t WHERE t.checkTime >=concat(date_sub("+curdate+", INTERVAL "+gropType+") , ' 00:00:00') 	AND t.checkTime <=	concat(date_sub(curdate(), INTERVAL 0 day)  , ' 23:59:59')   "+sickWhere+")  t 	GROUP BY t.category ORDER BY t.category asc";
			PageList<Map> pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, null, null);
			
			if(pl.getResultList().size()>0){
				for(Map m:pl.getResultList()){
					String averageSystolicpressure= m.get("averageSystolicpressure").toString();
					String averageDiastolicpressure= m.get("averageDiastolicpressure").toString();
					m.put("averageSystolicpressure", ArithSolve.formatDoubleScaleFiveString(new Double(averageSystolicpressure), 0));
					m.put("averageDiastolicpressure", ArithSolve.formatDoubleScaleFiveString(new Double(averageDiastolicpressure), 0));
					
				}
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data",pl.getResultList());
			}else{
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "无数据");
			}
			return mm;
			
		}catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统开小差，稍后重试");
			
			return mm;	
		}
		
	}
	/**
	 * app手动添加保存血压
	* @Title: saveSickBPdata 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param type
	* @param @param token
	* @param @param deviceSN
	* @param @param sbp
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	@PostMapping("/saveSickBPdata/{type}/{token}")
	public Map saveSickBPdata(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam  String deviceSN,SickBPdata  sbp,String checkoutTime ) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			SickDetailInfo sdi =this.getSickDetailInfo(deviceSN);
			if(ChkUtil.isEmpty(sdi)){
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "此设备患者不存在");
				return mm;
			}
			sbp.setMode("-1");
			sbp.setCreater("cpapp");
			sbp.setUpdater("cpapp");
			sbp.setBpunique(sbp.getUnique());
			sbp.setUnique(null);
			sbp.setBpkey("cpapp");
			sbp.setKey(null);
			if(!ChkUtil.isEmpty(checkoutTime)){
				sbp.setCheckTime(Times.getStringToDate(checkoutTime, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
			}
			
			sbp.setDeviceSN(deviceSN);
			sbp.setSickId(sdi.getId_());
			sbp.setRemarks("cpapp手动添加血压保存");
			
			
			Integer level=checkBpLevel(sbp.getSystolicpressure(), sbp.getDiastolicpressure());
			sbp.setLevel(level.toString());
			this.mBaseDao.saveObject(sbp);
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
			
		}catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "保存失败");
		}
		return mm;
		
	}
	
/*	       
 *        
 *        标准检验判断血压等级
 *        血压等级,0:低,1:正常,2:正常高值,3:轻度,4:中度,5:高度
           0血压低：x<=90 || y<=60
			1正常血压：x<120 and y<80
			2正常偏高： x(120-139) || y(80-89)
			3轻度高血压：x(140-159) || y(90-99),x>=140 and  y<90
			4中度高血压：x(160-179) || y(100-109)
			5高度高血压：x>=180  ||  y>=110
	*/
	 
	public Integer checkBpLevel(Integer systolicpressure,Integer diastolicpressure ){
		int level=1;
		if(systolicpressure<=90 && diastolicpressure<=60){
			level=0;
		}else if(systolicpressure<120 &&  diastolicpressure<80){
			
			level=1;
			
		}else if((systolicpressure>=120 &&systolicpressure<=139)||(diastolicpressure>=80 && diastolicpressure<=89)){
			
			level=2;
		}else if((systolicpressure>=140 && systolicpressure<=159) ||(diastolicpressure>=90 && diastolicpressure<=99)){
			
			level=3;
			
		}else if((systolicpressure>=160 && systolicpressure<=179) ||(diastolicpressure>=100 && diastolicpressure<=109)){
			level=4;
			
		}else if((systolicpressure>=180  && diastolicpressure>=110)||(systolicpressure>=180  || diastolicpressure>=110)){
			level=5;
			
		}else if(systolicpressure>=140  && diastolicpressure<90){
			level=2;
		}else if((systolicpressure>=140 && diastolicpressure>=90)||(systolicpressure>=140 ||diastolicpressure>=90)){
			
			level=2;
			
		}
		
		return level;
		
		
	}
	
	
}